﻿using FarmSmartSleep.Common.Domain.BeginTable;
using FarmSmartSleep.Common.Dtos;
using FarmSmartSleep.Common.Infrastructure;
using MediatR;

namespace FarmSmartSleep.Organ.API.Application.SleepInfoCommands.FemaleBeginCommands
{
    public class ProBeginAllCreateHander : IRequestHandler<ProBeginAllCreateCommand, Result>
    {

        private readonly IBaseRepository<ProBegin> proBeginRepository;
        private readonly IBaseRepository<SleepInfor> sleepInforRepository;
        private readonly ILogger<ProBeginAllCreateCommand> logger;

        public ProBeginAllCreateHander(IBaseRepository<ProBegin> proBeginRepository, ILogger<ProBeginAllCreateCommand> logger, IBaseRepository<SleepInfor> sleepInforRepository)
        {
            this.proBeginRepository = proBeginRepository;
            this.logger = logger;
            this.sleepInforRepository = sleepInforRepository;
        }

        /// <summary>
        /// 批量添加后裔期初
        /// </summary>
        /// <param name="request">批量添加后裔期初请求对象</param>
        /// <param name="cancellationToken"></param>
        /// <returns>批量添加后裔期初响应对象</returns>
        public async Task<Result> Handle(ProBeginAllCreateCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var result = new Result();
                request.Datas.ForEach(c =>
                {
                    c.CreateTime=DateTime.Now;
                    var info = sleepInforRepository.GetAll().FirstOrDefault(c => c.SleepInforId == c.SleepInforId);
                    if (info != null)
                    {
                        info.StayStatus = 1;
                        info.RecordcottageId = c.CottagesId;
                        info.FieIdId = c.FieId;
                        result.Code += sleepInforRepository.Update(info);
                    }
                });
                result.Code =await proBeginRepository.AddRange(request.Datas);
                logger.LogInformation("批量添加后裔期初信息方法调用成功");
                return result;
            }
            catch (Exception ex )
            {
                logger.LogError("批量添加后裔期初信息方法调用出错" + ex);
                throw;
            }
        }
    }
}
